<script setup>
import { ref,onMounted } from "vue";
import DyMap from '../../components/DyMap.vue';
// import Map from '../../components/Map.vue';
import {formatDate,getLastMonthRange,getStartAndEndOfMonth,hourMinute} from '../../tools/timeDate' 
import CChartBarExample from '../charts/CChartBarExample.vue'
import officialSquib from '../../components/DyEcharts/officialSquib.vue'
// import { Vue3SeamlessScroll } from "vue3-seamless-scroll";
import CarouselList from '../../components/CarouselList/index.vue' //预警（饼图）
import officialLength from '../../components/DyEcharts/officialLength.vue' //分区供水量（柱状图）
import officialPipe from '../../components/DyEcharts/officialPipe.vue' //当日取水（折线图）
import bus from '../../tools/eventBus'
import {dataFactoryFn,waterIntakingFn,PostUserAuth,PostGisInfo,PostFqsQuery,PostStatistics,PostGetToken,PostGetSubzoneMessage,PostGetSubzoneData} from '../../http/http'

import Legend from '../theme/Legend.vue'

// 水质
const periodDataList1 = ref([]); 
const periodDataTitle=ref([
 {name:'水质点'},
 {name:'监测类型',slots:true},
 {name:'监测值'},
 {name:'时间'},
//  {name:'单位'},
])
// 流量实时数据
const flowList=ref([])
const flowTitle=ref([
 {name:'流量点'},
//  {name:'监测类型'},
 {name:'监测值'},
 {name:'时间'},
//  {name:'单位'},
])
const pressureTitle=ref([
 {name:'压力点'},
//  {name:'检测类型'},
 {name:'监测值'},
 {name:'时间'},
//  {name:'单位'},
])
const pressureList=ref([])
// 显隐折叠菜单栏
const isTrue=ref(false)
const waterTitle=ref([
 {name:'水质点'},
 {name:'PH'},
 {name:'浊度'},
//  {name:'二氧化氯'},

])
// 昨日
const Time_start=ref('')
const Time_end=ref('')
// 上个月
const Time_startM=ref('')
const Time_endM=ref('')
// 今日供水
const todayW=ref(0)
let xData = ref([])
let yData = ref([])

let Yesterday=ref(0)// 昨日供水
let YesterM=ref(0)
let ThisM=ref(0)

let isActive=ref(false)

// 获取文件所在地址
const pathName = window.document.location.pathname;
const pathUrl = pathName.substring(0, pathName.lastIndexOf('/'));

// 报警分析统计
const statistics=ref([])

// 总量
let totalVal=ref([
   {
    id:1,
    img:'/icon/Gsr.png',
    title:"昨日供水总量",
    num:0,
   },
   {
    id:2,
    img:"/icon/Qsr.png",
    title:"当日供水总量",
    num:0,
   },
   {
    id:3,
    img:"/icon/Gsy.png",
    title:"上月供水总量",
    num:0,
   },
   {
    id:4,
    img:"/icon/Qsy.png",
    title:"当月供水总量",
    num:0,
   },
   ])
// 控制侧边菜单展开/收缩
const isExpand=localStorage.getItem('isExpand')==='true'
isTrue.value=isExpand
bus.on('unfoldable',(is)=>{
  isTrue.value=is
})

// 分区供水量
async function TokenFn(){
  const data={
    "Cid":"65b89ab9e138230b029e1093",
    "Aid":"111",
    "UserName":"sjdj",
    "Password":"Ss@12345678"
  }
  const TokenValue=await PostUserAuth(data)
  let Token=''
  if(TokenValue.data.Message=="OK")  Token=TokenValue.data.Response.Token
  const data1={
      "Token": Token,
      "conditions": [{"Field":"community","Operate":"=","Value":0,"Relation":"and"}],
      "fields": ["id", "_id", "pid", "name", "area", "center", "square", "lm"]
  }
  const gisInfo=await PostGisInfo(data1)
  let dataValue=[]

  if(gisInfo.data.Message=="OK")  dataValue=gisInfo.data.Response

  const timestampInSeconds = Math.floor(Date.now() / 1000);// 当前秒级时间戳


  let districtWater= await Promise.all(dataValue.map(async(item)=>{
    const FqsGs={
    "Token": Token,
    "did": item.id, 
    "dt":timestampInSeconds
    }
    let FqsValue=[]
    const FqsQuery=await PostFqsQuery(FqsGs)
    
    if(FqsQuery.data.Message=="OK")  FqsValue=FqsQuery.data.Response
    return {
      dayWater: FqsValue.today_flux,
      name:item.name,
      id:item.id,
      pname:item.pname
    }
  }))

  console.log(districtWater,'FqsValueFqsValueFqsValue');
  districtWater.forEach((item)=>{
    if(item.name!='鲁辰' && item.name!='鲁兴' && item.name!="东营能源集团"){
      xData.value.push(item.name)
      yData.value.push(item.dayWater)
    }
  })
}
// 和达-分区供水量接口-异步处理
// TokenFn()


// 92测试环境-分区供水量接口
async function PostGetTokenFn(){
   const token=await PostGetToken()
   console.log('token',token);
   let partitionID={}
   if(token.data==='ok') partitionID=await PostGetSubzoneMessage()
   let partition={}
   let partitionList=[]
   if(partitionID.data=='ok') partition= await PostGetSubzoneData()
   partitionList=partition.data
  console.log('partitionList',partitionList);
  
  partitionList.forEach((item)=>{
    if(item.name!='鲁辰' && item.name!='鲁兴' && item.name!="东营能源集团"){
      xData.value.push(item.name)
      yData.value.push(item.todayFlux)
    }
  })
}

PostGetTokenFn()

let StageV=ref([])
let StageT=ref([])
// 今日阶段供水量/小时
async function waterStage(){
  try{
     const res= await waterIntakingFn()
     StageV.value=[]
     StageT.value=[]
     const StageList=res.data
     // 今日供水总量
     totalVal.value[1].num=unitFn(StageList.totalDifference)     
     StageList.hourlyDifferences.forEach((item)=>{
      StageV.value.push(item.difference)
      StageT.value.push(hourMinute(item.time))
     })
  }catch (error) {
    console.error('Error fetching data:', error);
  }
}
onMounted(async () => {
   await waterStage()
})

function scheduleNextHourlyTask() {
    // 获取当前时间
    let now = new Date();
    let currentHour = now.getHours();

    // 计算下一个整点的时间
    let nextHour = currentHour + 1;
    let nextHourTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), nextHour, 0, 0, 0);
    let timeToNextHour = nextHourTime - now;
    // 设置定时器，在距离下一个整点的时间后触发
    setTimeout(function() {
        // 执行你的操作
        console.log('每小时整点操作');
        // 调度下一次任务
        scheduleNextHourlyTask();
        // 分区供水量
        // TokenFn()
        PostGetTokenFn()
    }, timeToNextHour);
}

// 启动定时任务
scheduleNextHourlyTask();

function dataFactoryFormData(type){
  // json格式转换成表单数据格式
  const formDataValue = new URLSearchParams(dataFactoryValue()).toString();
  dataFactoryFn(formDataValue).then((res)=>{
    let data=res.data
    if(data.code==200){
      if(type==='zr'){
          // Yesterday.value=reserveMantissa(data.data)
          totalVal.value[0].num=unitFn(reserveMantissa(data.data)) 
      }else if(type==='sy'){
        YesterM.value=reserveMantissa(data.data)
        totalVal.value[2].num=unitFn(reserveMantissa(data.data)) 
      }else if(type==='dy'){
        // ThisM.value=Number(reserveMantissa(data.data))
        totalVal.value[3].num=unitFn(reserveMantissa(data.data))
      }
    }
  })
}

// 单位处理/万
function unitFn(value){
  if(value>10000){
    return Number((value/10000).toFixed(0))
  }
  return Number((value/10000).toFixed(2))
}

// 保留尾数
function reserveMantissa(data){
  return data.reduce((sum,item)=>{
    return sum+item.rgsl
  },0).toFixed(2);
}
// 供水日期范围-水厂
function dataFactory(){
  // 日供水起止日期
  const today=new Date()
  const yesterday=new Date(today)
  yesterday.setDate(today.getDate()-1)
  Time_start.value=formatDate(yesterday),
  Time_end.value=formatDate(today)
  dataFactoryFormData('zr')
}
dataFactory()

// 上个月起止日期
function dataFactoryM(){
  Time_start.value=getLastMonthRange().start
  Time_end.value=getLastMonthRange().end
  dataFactoryFormData('sy')
}
dataFactoryM()

// 当月起止日期
function thisMonth(){
  Time_start.value=getStartAndEndOfMonth().start
  Time_end.value=getStartAndEndOfMonth().end
  dataFactoryFormData('dy')
}
thisMonth()
// 水厂入参
function dataFactoryValue(){
  return {
    datasetId:'02915d3c-e985-3e92-be1c-0341a3f15538',
    dataTime_start:Time_start.value,
    dataTime_end:Time_end.value
  }
}

let realTime=ref([])
// 流量压力水质实时数据
bus.on('realTime', (data) => {
  
  const value=data.target.slice(0, 4);
  const FbTime=data.t
  const today = new Date();
  const todayStr = today.toISOString().split('T')[0]; // 当日时间
  const SsDay=FbTime.split(' ')[0] // 实时数据时间
  // 过滤数据，保留今天的数据
  if(SsDay===todayStr){ // 时间对比-获取当天时间
    data.FbTime=FbTime.split(' ')[1]  
    if(value==='管网流量'){


      data.FbTarget=data.target
      
      // data.v=data.v+'m³/h' //添加单位
      data.v=ensureUnit(data.v,'m³/h')
      const dataSnId=data.sn+'_'+data.pointId
      const existingIndex=flowList.value.findIndex((item)=>item.sn+'_'+item.pointId===dataSnId)
      if(existingIndex!==-1){
        flowList.value.splice(existingIndex,1)
        flowList.value.push(data)
      }else{
        flowList.value.push(data)
      }
    }else if(value==='管网压力'){

      data.FbTarget=data.target

      if(data.v>1){
        data.v=(data.v/10000) // 压力值除10000
      }
      // data.v=data.v+'MPa' //添加单位
      data.v=ensureUnit(data.v,'MPa')
      const dataSnId=data.sn+'_'+data.pointId
      const existingIndex=pressureList.value.findIndex((item)=>item.sn+'_'+item.pointId===dataSnId)
      if(existingIndex!==-1){
        pressureList.value.splice(existingIndex,1)
        pressureList.value.push(data)
      }else{
        pressureList.value.push(data)
      }    
    }else if(value==='管网水质'){
      const Target=data.target
      data.FbTarget=Target.replace("管网水质", "")
      
      switch (data.FbTarget) {// 添加单位字段
        case '浊度':
          //  data.v=data.v+'NTU'
          data.v=ensureUnit(data.v,'NTU')
            break;
        case 'PH':
            data.v=data.v
            break;
        case '二氧化氯':
            // data.v=data.v+'mg/L'
            data.v=ensureUnit(data.v,'mg/L')
        break;
      }
      data.slots=true
      // 拼接唯一值
      const dataSnId=data.sn+'_'+data.pointId
      // 遍历-新数据替换旧数据
      const existingIndex = periodDataList1.value.findIndex(item => item.sn+'_'+item.pointId === dataSnId);
      if (existingIndex !== -1) {
          // 使用 splice 移除，并push到末尾
          periodDataList1.value.splice(existingIndex, 1);
          periodDataList1.value.push(data);
      } else {
          // 如果不存在，直接将新数据添加到数组的末尾
          periodDataList1.value.push(data);
      }      
    }
 }

})

// 创建一个函数来格式化数字并添加单位
function ensureUnit(value, unit) {
    if (typeof value === 'number') {
        return `${value}${unit}`;
    } else if (typeof value === 'string') {
        // 检查是否已经包含单位
        if (!value.endsWith(unit)) {
            return `${value}${unit}`;
        }
        return value;
    }
    return value;  // 如果不是数字或字符串，直接返回原值
}

// 报警分析统计接口
/*
{
    "startTime"开始时间非必填
    "endTime":"结束时间非必填
    "warnType":状态非必填（不天返回所有）
    "isActive":"1"固定值1必传
}
*/
function StatisticsFn(){
  PostStatistics({isActive:1 }).then((res)=>{
    const data=res.data
    if(data.message[0]=='success'){
      statistics.value=data.returnValue.result
    }
  })
}
StatisticsFn()

function LegendChang(){
  isActive.value=!isActive.value
}

</script>

<template>
  <div>
    <DyMap></DyMap>
<div class="container">
   <div :class="isTrue?'left-column':'left-column1'">
        <div class="leftBox">
          <div class="title">
            <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;报警分析</div>
          <div v-if="statistics.length">
            <official-squib :statistics="statistics"></official-squib>
          </div>
          </div>
        <div class="leftBox">
          <div class="title">
            <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;压力监测分析</div>
        <carousel-list :periodDataTitle="pressureTitle" :periodDataList="pressureList"></carousel-list>
        </div>
        <div class="leftBox">
          <div class="title">
            <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;水质监测分析</div>
          <carousel-list :slotValue="true" :periodDataTitle="periodDataTitle" :periodDataList="periodDataList1"></carousel-list>
        </div>
   </div>

    <div class="main-content">
        <div :class="isTrue?'map-content':'map-content1'">
          
          <div v-for="(item) in totalVal" :key="item.id" :class="isTrue?'map-top':'map-top1'">
            <img :class="isTrue?'map-img':'map-img1'" :src="pathUrl+item.img" />
            <span>
              <span :class="isTrue?'top_title':'top_title1'">{{ item.title }}</span>
              <span v-if="item.id==4" :class="isTrue?'total':'total1'">
                {{    totalVal[1].num+totalVal[3].num }}
              </span>
              <span v-else :class="isTrue?'total':'total1'">
                  {{ item.num }}
              </span>
              <span :class="isTrue?'unit1':'unit'"> 万m³</span>
            </span>
          </div>
          
          <!-- <div :class="isTrue?'map-top':'map-top1'">
            <img :class="isTrue?'map-img':'map-img1'" src="../../assets/images/取水日.png" />
            <span>
              <span>当日供水总量</span>
              <span :class="isTrue?'total':'total1'">
                {{todayW.toFixed(2)}}
                234万
              </span>m³
            </span>
          </div>
          <div :class="isTrue?'map-top':'map-top1'">
            <img :class="isTrue?'map-img':'map-img1'" src="../../assets/images/供水月.png" />
            <span>
              <span>上月供水总量</span>
              <span :class="isTrue?'total':'total1'">
                {{YesterM}}
                234万
              </span>m³
            </span>
          </div>
          <div :class="isTrue?'map-top':'map-top1'">
            <img :class="isTrue?'map-img':'map-img1'" src="../../assets/images/取水月.png" />
            <span>
              <span>当月供水总量</span>
              <span :class="isTrue?'total':'total1'">
                {{ThisM+todayW}}
                234万
              </span>m³
            </span>
          </div> -->
        </div>
    </div>
    <div class="right-column">
      <div class="rightBox">
        <div class="title">
          <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;分区供水量</div>
          <div v-if="xData.length">
           <officialLength :xData="xData" :yData="yData"></officialLength>
          </div>
      </div>
        <div class="rightBox">
          <div class="title">
            <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;今日供水量</div>
          <div v-if="StageT.length">
            <officialPipe :StageV="StageV" :StageT="StageT"></officialPipe>
          </div>
        </div>
        <div class="rightBox">
          <div class="title">
            <img style="width: 20px;" src="../../assets/images/icon_三角.png">&ensp;流量监测分析</div>
          <carousel-list :periodDataTitle="flowTitle" :periodDataList="flowList"></carousel-list>
          
        </div>
        <Legend v-if="isActive" class="legendBox"></Legend>
        <img class="isLegend" @click="LegendChang()" src="../../assets/images/图层@2x.png" alt="">
    </div>
</div>
</div>
</template>



<style lang="scss" scoped>
.container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.left-column {
  width: 336px;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  // padding-left:81px
}

.left-column1{
  width: 336px;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  padding-left:81px
}

.map-content{
  width: 410px;
  height: 20px;
  position: absolute;
  top: 6px;
  z-index: 99;
  display: flex;
  justify-content: space-between;
  left: 44%;
}
.map-content1{
  width: 625px;
  height: 20px;
  position: absolute;
  top: 10px;
  z-index: 99;
  display: flex;
  justify-content: space-between;
  left: 30%;
}
.map-top{
    width:24% ;
    height: 53px;
    background: #FFFFFF;
    border-radius: 10px;
    font-size: 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    opacity: 0.9;
  }
  .map-top1{
    width:136px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    background-image: linear-gradient(137deg, rgba(253,254,255,0.96) 21%, rgba(247,250,254,0.86) 100%);
    box-shadow: 0px 2px 8px 0px rgba(10,35,59,0.1);
    border-radius: 12px;
  }
  .top_title1{
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #435069;
    letter-spacing: 0;
    line-height: 14px;
    font-weight: 400;
    padding-right: 6px;
  }
  .top_title{
    font-family: PingFangSC-Regular;
    font-size: 8px;
    color: #435069;
    letter-spacing: 0;
    line-height: 14px;
    font-weight: 400;
  }
  
  .map-img{
    width: 20px;
    margin:-10px 6px 0 0;
  }
  .map-img1{
    width: 16px;
    margin:-27px 6px 0 0;
  }
  .unit{
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #747B8B;
    letter-spacing: 0;
    line-height: 18px;
    font-weight: 400;
  }
  .unit1{
    font-family: PingFangSC-Regular;
    font-size: 9px;
    color: #747B8B;
    letter-spacing: 0;
    line-height: 18px;
    font-weight: 400;
}
.leftBox{
  width: 336px;
  height: 216px;
  margin: 10px 13px 0px 5px;
  padding: 16px;
  background-image: linear-gradient(137deg, rgba(253,254,255,0.96) 21%, rgba(247,250,254,0.86) 100%);
  box-shadow: 0px 2px 8px 0px rgba(10,35,59,0.1);
  border-radius: 12px;

  .sunMoon{
    .r{
     padding-top: 16px;
    }
  }
}

.main-content {
  width: 80%;
  .total{
    font-size: 12px;
    font-family: Oswald-Regular;
    color: #2D2F33;
    letter-spacing: 0;
    line-height: 32px;
    font-weight: 400;
  } 
  .total1{
    //  font-size: 17px;
    font-family: Oswald-Regular;
    font-size: 22px;
    color: #2D2F33;
    letter-spacing: 0;
    line-height: 32px;
    font-weight: 400;
  }
}

.title{
  position: absolute;
  font-family: PingFangSC-Medium;
  font-size: 16px;
  color: #232426;
  line-height: 24px;
  font-weight: 500;
}

.right-column {
  width: 336px;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  right: 2%;
}
.rightBox{
  width: 336px;
  height: 216px;
  margin: 10px 13px 0px 5px;
  padding: 16px;
  background-image: linear-gradient(137deg, rgba(253,254,255,0.96) 21%, rgba(247,250,254,0.86) 100%);
  box-shadow: 0px 2px 8px 0px rgba(10,35,59,0.1);
  border-radius: 12px;
}
.legendBox{
  position: absolute; 
  bottom: 0%;
  right: 100%;
  z-index: 999;
}

.isLegend{
  position:absolute;
  bottom: -42px;
  width: 40px;
}
</style>